import SSHData from '@/components/shell/socket/SSHData'

export default class Socket {
  private socket: WebSocket;

  private readonly protocol: string;
  private readonly host: string;
  private readonly port: number;

  constructor (host: string, port: number, uri: string) {
    if (window.location.protocol === 'https:') {
      this.protocol = 'wss://'
    } else {
      this.protocol = 'ws://'
    }

    this.host = host
    this.port = port

    const url = this.protocol + this.host + ':' + this.port + '/' + uri
    this.socket = new WebSocket(url)
  }

  /**
   * 建立连接
   * @param onConnect
   * @param onData
   * @param onError
   * @param onClose
   */
  connect (
    onConnect: () => void,
    onData: (msg: string) => void,
    onError?: () => void,
    onClose?: () => void
  ) {
    // 连接建立时
    this.socket.onopen = event => {
      console.log('connection established', event)
      onConnect()
    }

    // 接受到数据时
    this.socket.onmessage = msgEvent => {
      const msg: string = msgEvent.data
      console.log('data', msg)
      onData(msg)
    }

    this.socket.onerror = ev => {
      console.log('error', ev)
      if (onError) {
        onError()
      }
    }

    this.socket.onclose = closeEvent => {
      console.log('close', closeEvent)
      if (onClose) {
        onClose()
      }
    }
  }

  /**
   * 发送操作命令
   * @param operate ( command, connect)
   * @param command
   */
  sendCmd (operate: string, command: string) {
    const data = new SSHData()
    // ssh 的连接信息
    data.host = '192.168.123.19'
    data.port = 5022
    data.username = 'xiang'
    data.password = '1213'

    data.operate = operate
    data.command = command

    this.sendSock(data)
  }

  private sendSock (data: SSHData) {
    if (this.socket.readyState === this.socket.OPEN) {
      // 若是ws开启状态
      this.socket.send(JSON.stringify(data))
    } else if (this.socket.readyState === this.socket.CONNECTING) {
      // 若是 正在开启状态，则等待1s后重新调用
      setTimeout(() => {
        this.sendSock(data)
      }, 1000)
    } else {
      // 若未开启 ，则等待1s后重新调用
      setTimeout(() => {
        this.sendSock(data)
      }, 1000)
    }
  }
}
